package com.licenta.fbApp.client;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.gwittit.client.facebook.ApiFactory;
import com.gwittit.client.facebook.FacebookApi.Permission;
import com.gwittit.client.facebook.entities.UserInfo;
import com.gwittit.client.facebook.xfbml.FbName;
import com.gwittit.client.facebook.xfbml.FbProfilePic;
import com.gwittit.client.facebook.xfbml.FbPromptPermission;
import com.gwittit.client.facebook.xfbml.Xfbml;
import com.gwittit.client.facebook.xfbml.FbProfilePic.Size;


public class DisplayUserInfo {


  public static Long getUid() {
    return ApiFactory.getInstance().getLoggedInUser();
  }

  public static boolean isMyself(Long uid) {
    return uid.equals(getUid());
  }

  static public class UserPic extends Composite {
    private VerticalPanel panel = new VerticalPanel();

    public UserPic() {
      this(getUid());
    }

    public UserPic(Long uid) {
      FbProfilePic pic = new FbProfilePic(uid, FbProfilePic.Size.normal);
      pic.setWidth("130px");
      panel.add(pic);
      Xfbml.parse(panel);
      initWidget(panel);
    }
  }

  /**
   * Widget that displays the user name.
   * 
   */
  static public class UserName extends Composite {
    private VerticalPanel panel = new VerticalPanel();

    public UserName() {
      this(getUid());
    }

    public UserName(Long uid) {
      FbName fbName = new FbName(uid, false);
      fbName.setUseyou(false);
      panel.add(fbName);
      Xfbml.parse(panel);
      initWidget(panel);
    }
  }

  /**
   * Widget that displays the user friends.
   * 
   */
  static public class UserFriends extends Composite {
    private static final int LOAD_STEP = 10;
    private VerticalPanel panel = new VerticalPanel();
    private FlowPanel friendsPanel = new FlowPanel();
    private Button loadMore = new Button("Load More");
    private Button showAll = new Button("Show all");
    private List<Long> uids;
    private int loadedCount = 0;
    private List<String> names;

    private final HorizontalPanel searchFriends = new HorizontalPanel();

    public UserFriends() {
      initWidget(panel);
      panel.add(loadMore);
      loadMore.setEnabled(false);
      loadMore.setTitle("Add more friends to the list");
      loadMore.addClickHandler(new ClickHandler() {
        
        public void onClick(ClickEvent event) {
          loadNext();
        }
      });
      
      panel.add(showAll);
      showAll.setEnabled(false);
      showAll.setTitle("Show all friends");
      showAll.addClickHandler(new ClickHandler() {
        
        public void onClick(ClickEvent event) {
          showFriends();
        }
      });

      searchFriends.add(new Label("   Search  "));
      final TextBox searchBox = new TextBox();
      searchBox.addKeyPressHandler(new KeyPressHandler() {

		
		public void onKeyPress(KeyPressEvent event) {
			showSelected(searchBox.getText());	
		}
      });
      
      searchFriends.add(searchBox);   
      panel.add(searchFriends);   
      
      panel.add(friendsPanel);
      ApiFactory.getInstance().friendsGet(new AsyncCallback<List<Long>>() {
        
        public void onSuccess(List<Long> result) {
          uids = result;
          loadNext();
          loadMore.setEnabled(true);
          showAll.setEnabled(true);
          
          List<String> fields = new ArrayList<String>();
          fields.add("first_name");
          fields.add("last_name");
          
          ApiFactory.getInstance().usersGetInfo(uids, fields, new AsyncCallback<List<UserInfo>>() {
            
            public void onSuccess(List<UserInfo> result) {
            	names = new ArrayList<String>();
              for (UserInfo i : result) {
                names.add(new String(i.getFirstName() + " " + i.getLastName()));
              }
            }
           
            
            public void onFailure(Throwable caught) {
              // TODO Auto-generated method stub
            }
          }); 
        }

        
        public void onFailure(Throwable caught) {
          // TODO Auto-generated method stub
        }
      });
    }

    private void showSelected ( String text) {
    	Vector<Long> valid = new Vector<Long>();

        List<String> fields = new ArrayList<String>();
        fields.add("first_name");
        fields.add("last_name");
                 
    	for (int i=0; i < names.size(); i++){
    		if (names.get(i).toUpperCase().indexOf(text.toUpperCase()) != -1){
    			valid.add(uids.get(i));
    		}
    	}

    	if (valid.size() < 5 * LOAD_STEP)
    	{
	    	friendsPanel.clear();
	    	
	    	for (int i = 0; i < valid.size(); i++) {
	            final Long uid = valid.get(i);
	            FbProfilePic friendPic = new FbProfilePic(uid, Size.square);
	
	            // remove the default link to facebook
	            friendPic.getElement().setAttribute("linked", "false");
	
	            // on click fire a FriendClickedEvent
	            friendPic.addDomHandler(new ClickHandler() {
	              
	              public void onClick(ClickEvent event) {
	                ApiFactory.getInstance().friendsGetAppUsers(new AsyncCallback<List<Long>>() {
	                  
	                  
	                  public void onSuccess(List<Long> result) {
	                    boolean isUsing = result.contains(uid);
	                    AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, isUsing));
	                  }
	                  
	                  
	                  public void onFailure(Throwable caught) {
	                    AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, false));
	                  }
	                });
	              }
	            }, ClickEvent.getType());
	            friendsPanel.add(friendPic);
	          }
	    	Xfbml.parse(friendsPanel);
    	}
    }    	
    
    private void loadNext() {
      loadMore.setEnabled(false); // prevent too many clicks
      
      if ( loadedCount == 0 ){
    	  friendsPanel.clear();
      }
      
      for (int i = loadedCount; i < loadedCount + LOAD_STEP && i < uids.size(); i++) {
        final Long uid = uids.get(i);
        FbProfilePic friendPic = new FbProfilePic(uid, Size.square);

        // remove the default link to facebook
        friendPic.getElement().setAttribute("linked", "false");

        // on click fire a FriendClickedEvent
        friendPic.addDomHandler(new ClickHandler() {
          
          public void onClick(ClickEvent event) {
            ApiFactory.getInstance().friendsGetAppUsers(new AsyncCallback<List<Long>>() {
              
              
              public void onSuccess(List<Long> result) {
                boolean isUsing = result.contains(uid);
                AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, isUsing));
              }
              
              
              public void onFailure(Throwable caught) {
                AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, false));
              }
            });
            //AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid));
          }
        }, ClickEvent.getType());
        friendsPanel.add(friendPic);
      }
      Xfbml.parse(friendsPanel);
      loadedCount += LOAD_STEP;
      if (loadedCount < uids.size()) {
        loadMore.setEnabled(true);
      } else {
        loadedCount = uids.size();
      }
    }
    
    private void showFriends() {
    	showAll.setEnabled(false); // prevent too many clicks
    	loadedCount = 0;
    	friendsPanel.clear();
        for (int i = 0; i < uids.size(); i++) {
          final Long uid = uids.get(i);
          FbProfilePic friendPic = new FbProfilePic(uid, Size.square);

          // remove the default link to facebook
          friendPic.getElement().setAttribute("linked", "false");

          // on click fire a FriendClickedEvent
          friendPic.addDomHandler(new ClickHandler() {
            
            public void onClick(ClickEvent event) {
              ApiFactory.getInstance().friendsGetAppUsers(new AsyncCallback<List<Long>>() {
                
                
                public void onSuccess(List<Long> result) {
                  boolean isUsing = result.contains(uid);
                  AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, isUsing));
                }
                
                
                public void onFailure(Throwable caught) {
                  AppEventBus.getEventBus().fireEvent(new FriendClickedEvent(uid, false));
                }
              });
            }
          }, ClickEvent.getType());
          friendsPanel.add(friendPic);
        }
        Xfbml.parse(friendsPanel);   
        showAll.setEnabled(true);
      }
    
  }
  
  static public class PermissionGranter extends Composite {
    public PermissionGranter() {
      final VerticalPanel outer = new VerticalPanel();

      FbPromptPermission promptPerm = new FbPromptPermission(
        "Click to see create_event, create_note and publish_stream permission dialog",
        Permission.create_event, Permission.create_note, Permission.publish_stream);
      outer.add(promptPerm);
      Xfbml.parse(outer);
      initWidget(outer);
    }
  }

}